package com.study.service.Impl;

import com.study.constant.PasswordConstant;
import com.study.context.BaseContext;
import com.study.dto.AdministratorDTO;
import com.study.entity.Admin;
import com.study.exception.AccountLockedException;
import com.study.exception.AccountNotFoundException;
import com.study.exception.PasswordErrorException;
import com.study.mapper.AdminMapper;
import com.study.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    //    @Autowired
    private final AdminMapper adminMapper;

    @Autowired
    public AdminServiceImpl(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    /**
     * 添加管理员账号
     *
     * @param administratorDTO
     */
    @Override
    public void addAdministrator(AdministratorDTO administratorDTO) {
        log.info("添加管理员账号:{}", administratorDTO);
        Admin admin = new Admin();

        //拷贝属性
        BeanUtils.copyProperties(administratorDTO, admin);

        //赋值其他属性
        admin.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        admin.setCreateTime(LocalDateTime.now());
        admin.setCreateUser(BaseContext.getCurrentId());
        admin.setStatus(1);

        adminMapper.add(admin);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Admin login(String username, String password) {
        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException("账号不存在");
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException("密码错误");
        }

        if (admin.getStatus() == 0) {
            //账号被锁定
            throw new AccountLockedException("账号被锁定");
        }

        //3、返回实体对象
        return admin;
    }
}
